﻿namespace Away.Common.Mvc.Validation;

/// <summary>
/// 模型验证
/// </summary>
public class ValidatResultAttribute : ServiceFilterAttribute
{
    public ValidatResultAttribute() : base(typeof(ValidatResultFilter))
    {
    }
}

[ServiceInject(ServiceLifetime.Scoped, true)]
public class ValidatResultFilter : IAsyncResultFilter
{
    private readonly ILogger<ValidatResultFilter> _logger;
    public ValidatResultFilter(ILogger<ValidatResultFilter> logger)
    {
        _logger = logger;
    }

    public Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        if (context.ModelState.IsValid)
        {
            return next();
        }
        context.HttpContext.Response.StatusCode = 200;

        var data = context.ModelState.ToDictionary(o => FirstLowerCase(o.Key), o => o.Value?.Errors.Select(o => o.ErrorMessage).FirstOrDefault());
        context.Result = ApiResult.Ok(data, 400, "参数错误");
        _logger.LogInformation("接口参数错误：{}", JsonSerializer.Serialize(data));
        return next();
    }

    static string FirstLowerCase(string str)
    {
        if (string.IsNullOrWhiteSpace(str))
        {
            return str;
        }
        return str.Length == 1 ? str.ToLower() : char.ToLower(str[0]) + str[1..];
    }
}

